package cn.car91.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import cn.car91.R;
import cn.car91.activity.MainFragmentActivity;
import cn.car91.activity.SearchActivity;
import cn.car91.bean.City;
import cn.car91.config.InitApplication;
import cn.car91.http.HttpHandler;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.RegexUtil;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;

public class HeaderView extends LinearLayout {
	SharedPreferences sharedPreferences;

	static List<String> mCity;
	static List<City> cities;

	View header_default = null;
	View header_index = null;
	SliderMenu sliderMenu = null;

	View areaBtn = null;
	View personBtn = null;
	View searchBtn = null;
	// View scanBtn = null;

	DbUtils dbUtils;

	public static final String action = "area.change.broadcast.action";

	public HeaderView(Context context) {
		super(context);
		// sliderView = ((MainCar91Activity) context).getmSliderView();
		init();
	}

	public HeaderView(Context context, AttributeSet attributeSet) {
		super(context, attributeSet);
		// sliderView = ((MainCar91Activity) context).getmSliderView();
		init();
	}

	private void init() {
		LayoutInflater inflater = (LayoutInflater) getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.view_header, this);

		dbUtils = DbUtils.create(getContext());

		sharedPreferences = ((InitApplication) getContext()
				.getApplicationContext()).getPlacePreferences();

		header_default = findViewById(R.id.header_default);

		personBtn = findViewById(R.id.imgBtn_person);
		personBtn.setOnClickListener(onPersonClickListener);

		areaBtn = findViewById(R.id.area_select_text);
		areaBtn.setVisibility(GONE);
		areaBtn.setOnClickListener(onAreaClickListener);

		searchBtn = findViewById(R.id.imgBtn_search);
		searchBtn.setOnClickListener(onSearchClickListener);

		// scanBtn = findViewById(R.id.imgBtn_scan);
		// scanBtn.setOnClickListener(onScanClickListener);

		String cname = sharedPreferences.getString("cityName", "");
		if (RegexUtil.isNotNull(cname)) {
			((Button) areaBtn).setText(cname);
		} else {
			((Button) areaBtn).setText(getResources().getString(
					R.string.view_header_area));
		}

		if (cities == null) {
			HttpHandler.httpHandler.getAllCities(callBackPlace);
		}
	}

	public RequestCallBack callBackPlace = new RequestCallBack() {
		@Override
		public void onFailure(HttpException arg0, String arg1) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSuccess(ResponseInfo arg0) {
			cities = Car91JsonUtil.getDTOList(arg0.result.toString(),
					City.class);
			City c = new City();
			c.setCid(-1);
			c.setName("全国");
			cities.add(0, c);

			int cid = sharedPreferences.getInt("city", -1);
			mCity = new ArrayList<String>();
			for (City city : cities) {
				mCity.add(city.getName());
				if (cid != -1) {
					if (city.getCid() == cid) {
						((Button) areaBtn).setText(city.getName());
					}
				}
			}
		}
	};

	// 头部功能
	OnClickListener onAreaClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			try {
				HerilyAlertDialog.Builder builder = new HerilyAlertDialog.Builder(
						getContext());

				builder.setTitle("城市");
				builder.setItems(
						(String[]) mCity.toArray(new String[mCity.size()]),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int which) {
								// 点击后弹出窗口选择了第几项
								SharedPreferences.Editor editor = sharedPreferences
										.edit();
								editor.putInt("city", cities.get(which)
										.getCid());
								editor.putString("cityName", cities.get(which)
										.getName());
								editor.commit();
								((Button) areaBtn).setText(cities.get(which)
										.getName());

								try {
									if (getContext().getClass().equals(
											MainFragmentActivity.class)) {
										Intent intent = new Intent(action);
										intent.putExtra("city",
												cities.get(which).getCid());
										((MainFragmentActivity) getContext())
												.sendBroadcast(intent);
									}
								} catch (Exception e) {
								}
							}
						});
				HerilyAlertDialog alertDialog = builder.create();
				alertDialog.setCanceledOnTouchOutside(true);
				alertDialog.show();
			} catch (Exception e) {
				LogUtils.e("选项列表初始化失败:" + e.getLocalizedMessage());
			}
		}
	};

	OnClickListener onPersonClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			try {
				sliderMenu = (SliderMenu) getRootView().findViewById(
						R.id.slider_menu);
			} catch (Exception e) {
			}
			if (sliderMenu != null) {
				sliderMenu.toggle();
				final View view = ((ViewGroup) sliderMenu.getChildAt(0))
						.getChildAt(1);
				if (!sliderMenu.isOpen())
					view.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							sliderMenu.closeMenu();
							view.setOnClickListener(null);
						}
					});
				else
					view.setOnClickListener(null);
			}
		}
	};
	// OnClickListener onScanClickListener = new OnClickListener() {
	// @Override
	// public void onClick(View arg0) {
	// // TODO Auto-generated method stub
	// Intent intent = new Intent();
	// intent.setClass(getContext(), CaptureActivity.class);
	// getContext().startActivity(intent);
	// }
	// };

	OnClickListener onSearchClickListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			intent.setClass(getContext(), SearchActivity.class);
			getContext().startActivity(intent);
		}
	};
}
